<template>
  <el-container>
    <el-container>
      <el-main>
        <el-row class="function-button">
          <el-button type="success" size="small" round @click="refresh()"
            >刷新按钮</el-button
          >
          <el-collapse accordion class="accordion">
            <el-collapse-item>
              <template slot="title">
                筛选<i class="header-icon el-icon-info"></i>
              </template>
              <div>
                <el-button
                  class="queryBtn"
                  round
                  type="success"
                  style="margin-left: 10px"
                  @click="queryByCondition"
                  >查询</el-button
                >
                <el-button
                  class="queryBtn"
                  round
                  style="margin-left: 10px"
                  type="warning"
                  @click="resetJobQueryParams"
                  >重置</el-button
                >
              </div>
              <el-select
                style="width: 20%; margin-left: 40px"
                v-model="jobQueryParam.jobCategoryId"
                placeholder="请选择岗位类别"
                filterable
                ref="jobCategorySelect"
              >
                <el-option
                  v-for="item in categories"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                >
                </el-option>
              </el-select>
              <el-select
                style="width: 20%; margin-left: 40px"
                v-model="jobQueryParam.name"
                placeholder="请选择岗位名称"
                filterable
              >
                <el-option
                  v-for="item in jobNameAndIdList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                >
                </el-option>
              </el-select>
              <el-input
                style="width: 20%; margin-left: 40px"
                placeholder="输入薪资范围,如(3k-5k)"
                size="samll"
                prefix-icon="el-icon-search"
                v-model="jobQueryParam.monthSalary"
              >
              </el-input>
              <!-- 城市选择 -->
              <el-cascader
                size="large"
                style="width: 20%; margin-left: 40px"
                :options="regionData"
                v-model="jobQueryParam.addressId"
                @change="handleChangeAtQuerying(jobQueryParam.addressId)"
                :props="{ checkStrictly: true }"
                placeholder="工作地点(省 / 市 / 区)"
              >
              </el-cascader>
              <el-date-picker
                style="width: 20%; margin-left: 40px"
                type="datetimerange"
                v-model="jobQueryParam.createTime"
                :picker-options="pickerOptions"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                align="right"
                :default-time="['00:00:00', '23:59:59']"
                value-format="yyyy-MM-dd HH:mm:ss"
              >
              </el-date-picker>
            </el-collapse-item>
          </el-collapse>
        </el-row>
        <template>
          <el-table
            ref="jobTable"
            :header-cell-style="{ 'text-align': 'center' }"
            :cell-style="{ 'text-align': 'center' }"
            v-loading="loading"
            :data="jobs"
            fit
            max-height="100vh"
            size="medium "
            class="tableStyle"
            highlight-current-row
            row-key="id"
            tooltip-effect="dark"
          >
            <el-table-column type="expand">
              <template slot-scope="props">
                <el-form label-position="left" inline class="demo-table-expand">
                  <el-form-item label="职位描述">
                    <span>{{ props.row.description || '无' }}</span>
                  </el-form-item>
                  <el-form-item label="工作福利">
                    <span>{{ props.row.welfare || '无' }}</span>
                  </el-form-item>
                </el-form>
              </template>
            </el-table-column>
            <el-table-column prop="createTime" label="发布时间" width="100">
              <template slot-scope="scope">
                {{ scope.row.createTime | dateFMT }}
              </template>
            </el-table-column>
            <el-table-column prop="jobName" label="岗位名称" width="100">
            </el-table-column>
            <el-table-column prop="requireEduId" label="学历">
              <template slot-scope="scope">
                <span>{{
                  educations.find((item) => item.id === scope.row.requireEduId)
                    .name || ''
                }}</span>
              </template>
            </el-table-column>
            <el-table-column
              prop="requireExperienceId"
              label="工作经验"
              width="150"
            >
              <template slot-scope="scope">
                <span>{{
                  experience.find(
                    (item) => item.id === scope.row.requireExperienceId
                  ).name || ''
                }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="jobCategoryId" label="职位分类" width="150">
              <template slot-scope="scope">
                <span>{{
                  categories.find((item) => item.id === scope.row.jobCategoryId)
                    .name || ''
                }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="companyId" label="所属企业">
              <template slot-scope="scope">
                <span>{{
                  companyIdAndNameAndCodeList.find(
                    (item) => item.id === scope.row.companyId
                  ).name || ''
                }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="monthSalary" label="月薪"></el-table-column>
            <el-table-column prop="workAddress" label="工作地点" width="200">
            </el-table-column>
            <el-table-column prop="updateTime" label="更新时间" width="100">
              <template slot-scope="scope">
                {{ scope.row.createTime | dateFMT }}
              </template>
            </el-table-column>
            <el-table-column fixed="right" label="操作" width="150">
              <template slot-scope="scope">
                <el-button
                  :type="scope.row.hasDelivery ? 'danger' : 'primary'"
                  @click="handFindJob(scope.row)"
                  :disabled="scope.row.hasDelivery ? true : false"
                  size="small"
                  >{{
                    scope.row.hasDelivery ? '已投递' : '投递简历'
                  }}</el-button
                >
                <!-- <el-button
                  type="danger"
                  @click="handDel(scope.row)"
                  size="small"
                  >删除</el-button
                > -->
              </template>
            </el-table-column>
          </el-table>
        </template>
        <div class="block">
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            :page-sizes="[10, 20, 50, 100]"
            :page-size="pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            hide-on-single-page
          >
          </el-pagination>
        </div>
      </el-main>
    </el-container>
  </el-container>
</template>

<script>
import { regionData, CodeToText } from 'element-china-area-data';
import throttle from 'lodash/throttle'; //
import { mapGetters } from 'vuex';
import { reqQueryResumeById } from '../ResumeMng/api/ResumeMngApi';
export default {
  name: 'FindJob',
  data() {
    return {
      search: '', // 前端模糊查询公司名称
      isAdd: false, // 模态窗口状态标识
      loading: false,
      currentPage: 1,
      pageSize: 10,
      total: 0,
      centerDialogVisible: false, // 模态窗口启用开关
      fullscreenLoading: false,
      jobForm: {
        companyId: 0,
      }, // 岗位添加/修改表单
      companys: [], // 企业列表
      regionData: regionData,
      selectedProvince: [],
      jobQueryParam: {
        jobCategoryId: undefined, // 搜索框，职位分类
        name: '', // 搜索框 职位名称
        createTime: new Date(), // 发布时间
        monthSalary: '', // 月薪
      },
      jobs: [], // 存放工作名称列表
      companyName: '', // 选中的企业名称
      educations: [], // 学历列表
      experience: [], // 工作经验列表
      condition: {},
      jobNames: {}, // 职位名称列表
      categoryName: '', // 分类名称
      // 时间选择快捷键
      pickerOptions: {
        shortcuts: [
          {
            text: '最近一周',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit('pick', [start, end]);
            },
          },
          {
            text: '最近一个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit('pick', [start, end]);
            },
          },
          {
            text: '最近三个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit('pick', [start, end]);
            },
          },
        ],
      },
    };
  },
  computed: {
    // 用户
    ...mapGetters(['name', 'description', 'loginId']),
    // 岗位
    ...mapGetters('PostPostingMng', ['jobIPage', 'jobList']),
    // 企业
    ...mapGetters('CompanyMng', ['companyIdAndNameAndCodeList']),
    // 工作分类
    ...mapGetters('JobCategoryMng', ['categories', 'jobNameAndIdList']),
    // 数据字典
    ...mapGetters('DictMng', ['educationList', 'experienceList']),
  },
  watch: {
    // 学历
    educationList() {
      this.$set(this, 'educations', this.educationList);
    },
    // 工作经验
    experienceList() {
      this.$set(this, 'experience', this.experienceList);
    },
    //对应类别下的 工作名称
    jobNameAndIdList() {
      this.$set(this, 'jobNames', this.jobNameAndIdList);
    },

    'jobQueryParam.jobCategoryId'(newValue, oldValue) {
      this.jobQueryParam.jobName = '';
      if (newValue) {
        // this.jobNames = [];
        // 发送请求
        this.$store.dispatch('JobCategoryMng/getIdAndNameList', newValue);
      }
    },
    'jobForm.jobCategoryId'(newValue, oldValue) {
      if (this.isAdd) {
        // 清空表单里岗位名称栏
        this.jobForm.name = '';
      }
      if (newValue) {
        // this.jobNames = [];
        // 发送请求
        this.$store.dispatch('JobCategoryMng/getIdAndNameList', newValue);
      }
    },
    jobList() {
      this.$set(this, 'jobs', this.jobList);
      this.loading = false;
    },
    jobIPage() {
      if (this.jobIPage.currentPage) {
        this.currentPage = this.jobIPage.currentPage;
      }
      if (this.jobIPage.pageSize) {
        this.pageSize = this.jobIPage.pageSize;
      }
      if (this.jobIPage.total) {
        this.total = this.jobIPage.total;
      }
    },
  },
  mounted() {
    // 获取企业列表
    this.getCompanyList();
    // 获取职位分类列表
    this.getCategories();
    // 获取学历列表
    this.getEducationList();
    // 获取工作经验列表
    this.getExperienceList();
    // 获取岗位列表
    this.getJobList();
  },
  methods: {
    // 获取工作经验列表  -- 从数据字典中获取
    async getExperienceList() {
      // 查询学历id
      let dict = await this.$store.dispatch(
        'DictMng/getDictIdByName',
        '工作经验'
      );
      if (dict && dict.id) {
        this.$store.dispatch('DictMng/getExperienceListByParentId', dict.id);
      } else {
        this.$message({
          message: '返回的学历编号为空',
          type: 'error',
          duration: 1 * 1000,
        });
      }
    },
    // 获取学历列表
    async getEducationList() {
      // 查询学历id
      let dict = await this.$store.dispatch('DictMng/getDictIdByName', '学历');
      if (dict && dict.id) {
        this.$store.dispatch('DictMng/getEduListByParentId', dict.id);
      } else {
        this.$message({
          message: '返回的学历编号为空',
          type: 'error',
          duration: 1 * 1000,
        });
      }
    },

    // 类别选择
    jobCategorySelectChange(val) {
      let obj = this.categories.find((item) => {
        return item.id == val;
      });
      this.jobForm.jobCategoryName = obj.name;
    },
    // 绑定函数重新加载一下组件
    jobNameSelectChange() {
      this.$forceUpdate();
    },
    // 获取职位分类列表
    getCategories() {
      this.$store.dispatch('JobCategoryMng/getCategories');
    },

    // 重置查询参数
    resetJobQueryParams() {
      this.jobQueryParam = {};
    },
    // 条件查询
    async queryByCondition() {
      // 起始发布日期
      let createTimeStart = {};
      // 截止发布日期
      let createTimeEnd = {};
      if (this.jobQueryParam.createTime) {
        if (this.jobQueryParam.createTime[0]) {
          createTimeStart = this.jobQueryParam.createTime[0];
        }
        if (this.jobQueryParam.createTime[1]) {
          createTimeEnd = this.jobQueryParam.createTime[1];
        }
      }
      // 初始化条件查询参数
      this.condition = {
        ...this.jobQueryParam,
        companyId: this.companyRowId,
        createTimeStart,
        createTimeEnd,
      };
      await this.getJobList();
      this.$nextTick(() => {
        this.$message({
          message: '查询成功',
          type: 'success',
          duration: 1 * 1000,
        });
      });
    },

    // 获取公司信息列表
    getCompanyList() {
      this.$store.dispatch('CompanyMng/queryForNameAndIdAndCode').then(() => {
        this.loading = false;
      });
    },
    // 查询岗位信息
    getJobList() {
      this.loading = true;
      let params = {
        currentPage: this.currentPage,
        pageSize: this.pageSize,
        condition: this.condition || {},
      };
      this.$store.dispatch('PostPostingMng/getJobList', params).then(() => {
        this.loading = false;
      });
    },

    // 每页显示多少条
    handleSizeChange(val) {
      this.pageSize = val;
      this.getCompanyList();
    },
    // 当前页
    handleCurrentChange(val) {
      this.currentPage = val;
      this.getCompanyList();
    },
    // 删除岗位
    handDel(row) {
      let result;
      this.$confirm('此操作将永久删除该记录, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        center: true,
      })
        .then(async () => {
          result = await this.$store.dispatch('PostPostingMng/delJob', [
            row.id,
          ]);
          this.$message({
            message: result.message,
            type: 'success',
            duration: 2 * 1000,
          });
          this.getJobList();
        })
        .catch(() => {
          this.$message({
            message: result.message,
            type: 'success',
            duration: 2 * 1000,
          });
        });
    },

    // 刷新列表
    refresh: throttle(async function () {
      this.currentPage = 1;
      await this.getJobList();
      this.$message({
        message: '刷新成功',
        type: 'success',
        duration: 1 * 1000,
      });
    }, 800),

    // 新增岗位
    handleAdd() {
      if (!this.jobForm.jobCategoryId) {
        this.jobNames = [];
      }
      this.jobForm = {};
      this.jobForm.companyId = this.companyRowId;
      this.jobForm.companyName = this.companyName;

      if (this.$refs.jobForm) {
        this.resetForm('jobForm');
      }
      this.isAdd = true;
      this.centerDialogVisible = true;
    },

    handFindJob(row) {
      let resumeId = 0;
      if (this.description === '学生用户') {
        // 查询学生简历信息
        reqQueryResumeById(this.loginId).then(async (res) => {
          // 返回学生简历信息
          if (!res.data.flag) {
            resumeId = res.data.resumeInfo.id;
          }
          let params = {
            jobId: row.id,
            resumeId,
            studentId: this.loginId,
            companyId: row.companyId,
          };
          let arr = [];
          arr.push(params);
          await this.$store.dispatch(
            'ResumeDeliveryStore/batchAddResumeDelivery',
            arr
          );
          this.$message.success('投递成功');
          this.getJobList();
        });
      }
    },
    // 城市选择--筛选
    handleChangeAtQuerying(addressId) {
      var loc = '';
      var locId = '';
      for (let i = 0; i < addressId.length; i++) {
        loc += CodeToText[addressId[i]] + '/';
        locId += addressId[i] + '-';
      }
      loc = loc.substring(0, loc.length - 1);
      locId = locId.substring(0, locId.length - 1);
      //工作地点字符串
      this.$set(this.jobQueryParam, 'workAddress', loc);
      //工作地点编号
      this.$set(this.jobQueryParam, 'workAddressId', locId);
    },
    // 城市选择
    handleChange(addressId) {
      var loc = '';
      // for (let i = 0; i < this.selectedJob.length; i++) {
      //   // this.$refs["cascader"].getCheckedNodes()[0].label 获取选中的label
      //   loc += this.$refs['cascader'].getCheckedNodes()[0].label;
      // }
      var locId = '';
      for (let i = 0; i < addressId.length; i++) {
        loc += CodeToText[addressId[i]] + '/';
        locId += addressId[i] + '-';
      }
      loc = loc.substring(0, loc.length - 1);
      locId = locId.substring(0, locId.length - 1);
      //工作地点字符串
      this.$set(this.jobForm, 'workAddress', loc);
      //工作地点编号
      this.$set(this.jobForm, 'workAddressId', locId);
    },

    // 点击左侧企业树行
    async companyTreeRowClick(row) {
      this.loading = true;
      // 根据企业编号查询岗位集合
      this.companyRowId = row.id;
      this.companyName = row.name;
      // 封装查询条件
      this.condition.companyId = row.id;
      this.getJobList();
    },
  },
};
</script>

<style lang="scss" scoped>
/* 表格扩展样式 */
// 表格扩展样式
.demo-table-expand {
  font-size: 0;
}

.demo-table-expand label {
  width: 90px;
  color: #99a9bf;
}

.demo-table-expand .el-form-item {
  margin-right: 0;
  margin-bottom: 0;
  width: 50%;
}

.function-button {
  margin-bottom: 10px;
}

// 折叠满样式 -- 搜索栏
.accordion {
  text-align: center;
  div {
    margin-bottom: 20px;
  }
  .queryBtn {
    // text-align: center;
  }
}

// 分页插件居中对齐
.block {
  text-align: center;
}
</style>
